import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.List;

/**
 * Copyright (c) 2017-2018, Daniel Jiang (thorqq@163.com).
 *
 * Licensed under the GNU GENERAL PUBLIC LICENSE, Version 3 (the "License");
 * 
 * Copyright (C) 2007 Free Software Foundation, Inc. [http://fsf.org/]
 */

/**
 * @author THORQQ
 *
 */
public class Utils
{
	public static class CommandResult
	{
		public String output;
		public int exitValue;
	}
	
	public static CommandResult runCommand(List<String> command)
	{
		StringBuffer cmdbuf = new StringBuffer();
		for(String cmd : command)
		{
			cmdbuf.append(cmd).append(" ");
		}
		cmdbuf.setLength(cmdbuf.length() - 1);
		System.out.println(cmdbuf.toString());
		
		CommandResult cr = new CommandResult();
		try
		{

			ProcessBuilder builder = new ProcessBuilder();
			builder.command(command);
			builder.redirectErrorStream(true);
			Process p = builder.start();

			// 1. start
			BufferedReader buf = null; // 保存ffmpeg的输出结果流
			String line = null;
			// read the standard output

			buf = new BufferedReader(new InputStreamReader(p.getInputStream()));

			StringBuffer sb = new StringBuffer();
			while ((line = buf.readLine()) != null)
			{
				sb.append(line);
				continue;
			}
			p.waitFor();// 这里线程阻塞，将等待外部转换进程运行成功运行结束后，才往下执行
			
			cr.exitValue = p.exitValue();
			cr.output = sb.toString();// 得到视频流
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}
		
		return cr;
	}
	
	public static void getFile(String fileDir, List<File> fileList)
	{
		// List<File> fileList = new ArrayList<File>();
		File file = new File(fileDir);
		File[] files = file.listFiles();// 获取目录下的所有文件或文件夹
		if (files == null)
		{// 如果目录为空，直接退出
			return;
		}
		// 遍历，目录下的所有文件
		for (File f : files)
		{
			if (f.isFile())
			{
				fileList.add(f);
			}
			else if (f.isDirectory())
			{
				// System.out.println(f.getAbsolutePath());
				getFile(f.getAbsolutePath(), fileList);
			}
		}

	}

    
	public static void writeFile(String filename, List<String> content) throws Exception
	{
		OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(filename), "gbk");
		BufferedWriter writer = new BufferedWriter(write);
		for (String row : content)
		{
			writer.write(row);
			writer.write("\r\n");
		}
		writer.close();
	}
}
